/**
 * 统一处理虚拟拖拽实现函数 - 注意区分不同的方向哈，这里仅做数据处理，具体的宽高变化，还得自行传入函数执行
 */
let startX = 0;
let startY = 0;

export function mousedownHandler(
  e: MouseEvent,
  direction: "lr" | "tb",
  callback: (diff: number) => void,
  success?: () => void
) {
  // 1. 记录初始位置
  startX = e.clientX;
  startY = e.clientY;

  // 2. 通过 window 实现流畅的拖拽
  window.addEventListener("mousemove", mousemoveHandler);
  window.addEventListener("mouseup", mouseupHandler);

  function mousemoveHandler(e: MouseEvent) {
    e.preventDefault();
    const diff = direction === "lr" ? e.clientX - startX : e.clientY - startY;
    if (direction === "tb") {
      document.querySelector("html")!.style.cursor = "ns-resize";
    } else {
      document.querySelector("html")!.style.cursor = "ew-resize";
    }
    callback(diff);
  }
  function mouseupHandler() {
    document.querySelector("html")!.style.cursor = "";

    window.removeEventListener("mousemove", mousemoveHandler);
    window.removeEventListener("mouseup", mouseupHandler);
    success && success();
  }
}
